Kurt Hsu's blog

The Rails developer in taiwan.


  • 首頁

  • 標籤

  • 分類

  • 歸檔

[Rails]利用 request direct_to 原本頁面

發表於 2018-04-15 更新於 2019-08-21 分類於 Rails

參考文章:
How to redirect to previous page in Ruby On Rails?(stackoverflow)

Ruby on Rails 實戰聖經

前言


redirect_to :back這個簡單回上一頁的方法似乎在Rails5不能使用了!
這時候我們可以利用request和session去做到導回前一頁的功能。

這裡的狀況:
有A和B頁面都可以過去C頁面編輯一篇文章,但從A頁面編輯完後要回到A,B則回到B,也就是說要做到這樣子:

A > C > A
B > C > B

如何實作?

實作


在C的controller裡的edit和update加入兩行

C_controller.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
def edit
@article = Article(params[:id])
session[:return_to] ||= request.referer
end

def update
@article = Article.find(params[:id])
if @article.update(post_params)
redirect_to session[:return_to]
session.delete(:return_to)
flash[:notuce] = "Update Success"
else
redirect_to root, alert: "Something wrong..."
end
end

private

def post_params
params.require(:article).permit(:content)
end

原理是用request.referer把前一頁的網址先存在session裡面,update的時候在導回剛剛存的網址頁。

所以我在A頁面的時候對某篇文章按編輯到C頁面觸發他的edit方法,這時候把前一頁也就是A的網址存下來,編輯完送出後觸發C的update導回剛剛存的A網址頁面,同理B也是一樣,我們就可以做到:

A > C > A
B > C > B

另外剛剛的update可以簡寫如下:

1
2
3
4
5
6
7
8
def update
@article = Article.find(params[:id])
if @article.update(post_params)
redirect_to session.delete(:return_to), notice: "Update Success"
else
redirect_to root, alert: "Something wrong..."
end
end

補充


request是用戶端發送請求的東西,例如header等等,當然也有response對象,可以參考

Ruby on Rails 指南

# Rails # request # direct_to
[Rails]AASM套件教學
[Rails] simple_form 簡易使用
  • 文章目錄
  • 本站概要

Kurt Hsu

Progress One Percent Every Day
171 文章
55 分類
163 標籤
RSS
  1. 1. 前言
  2. 2. 實作
  3. 3. 補充
© 2020 Kurt Hsu
由 Hexo 強力驅動 v3.8.0
|
主題 – NexT.Muse v7.3.0